package com.sunnyweather.android

import android.Manifest
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.sunnyweather.android.logic.Repository
import com.sunnyweather.android.logic.service.AMapPositionService
import com.sunnyweather.android.logic.util.LogUtil
import com.sunnyweather.android.ui.weather.WeatherActivity

class MainActivity : AppCompatActivity() {

    companion object{
        var runningInstance: MainActivity?=null
    }

    private var locationPermissionFlag=0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_layout)

        //权限申请
        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),1)
        }
        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),2)
        }
        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_BACKGROUND_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION),3)
        }
        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),4)
        }
        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),5)
        }



        runningInstance=this
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when(requestCode){
            1->{
                if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    LogUtil.d("Permission Fine Location","OK")
                    AMapPositionService.start()
                    Toast.makeText(this,"正在定位中......",Toast.LENGTH_SHORT).show()
                }else{
                    Toast.makeText(this,"拒绝精确定位权限将无法自动获取所在地天气",Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onDestroy() {
        runningInstance=null
        super.onDestroy()
    }
}